package cn.kgc.rbac.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author: mosin
 * @version: v1.0  2023/1/29
 */
@Configuration
public class ShiroConfig {

    //shiroFilter
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 创建集合  设置资源的认证权限
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("/api/**", "anon");
        map.put("/captcha/getCaptcha", "anon");
        map.put("/css/**", "anon");
        map.put("/extend/**", "anon");
        map.put("/images/**", "anon");
        map.put("/js/**", "anon");
        map.put("/lib/**", "anon");
        map.put("/user/login", "anon");
        map.put("/**", "user");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }

    //DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager  defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        //记住我
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        SimpleCookie sck = new SimpleCookie("rmber");
        sck.setMaxAge(60*3); //  60s
        cookieRememberMeManager.setCookie(sck);
        defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager);

        return  defaultWebSecurityManager;
    }

    //    REALM
    @Bean
    public Realm realm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //MD5
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        //设置散列次数
        hashedCredentialsMatcher.setHashIterations(50);
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return customerRealm;
    }

}
